/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.storage.web;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.storage.common.ServerResponse;
import com.jeesite.modules.storage.entity.Category;
import com.jeesite.modules.storage.entity.Order;
import com.jeesite.modules.storage.service.OrderService;
import com.jeesite.modules.storage.util.WebUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 订单Controller
 */
@Controller(value = "weborder")
@RequestMapping(value = "${adminPath}/storage/order")
public class OrderController extends BaseController {

    @Autowired
    private OrderService orderService;

    /**
     * 查询列表
     */
    @RequestMapping(value = {"list", ""})
    public String list(Order order, Model model) {
        model.addAttribute("order", order);
        return "modules/storage/order/list";
    }

    /**
     * 查询列表数据
     */
    @RequestMapping(value = "listData")
    @ResponseBody
    public Page<Map> listData(Order order,HttpServletRequest request, HttpServletResponse response) {
        Page page = new Page<>(request, response);
        return orderService.getListPageForManage(order.getStatus(),page.getPageSize(),page.getPageNo());
    }

    /**
     * 导出数据
     */
    @RequestMapping(value = "exportData")
    public void exportData(HttpServletResponse response) {
        try {
            Workbook workbook = getWorkbook("/template/订单 - 大仓库.xlsx");
            Sheet sheet = workbook.getSheetAt(0);
             List<Map> maps =   orderService.getListForManage("待发货",Integer.MAX_VALUE,1);
             for (Integer i = 0 ; i < maps.size() ; i ++){
                 Map map = maps.get(i);
                 Row row = getRow(sheet,i + 1);
                 Integer cellNum = 0;
                 getCell(row,cellNum++).setCellValue(i+1);
                 String orderId = String.valueOf(map.get("orderId"));
                 getCell(row,cellNum++).setCellValue(orderId);
                 getCell(row,cellNum++).setCellValue(String.valueOf(map.get("createDate")));
                 getCell(row,cellNum++).setCellValue(String.valueOf(map.get("nickName")));
                 getCell(row,cellNum++).setCellValue(Double.parseDouble( String.valueOf(map.get("total"))));
                 getCell(row,cellNum++).setCellValue(Integer.parseInt( String.valueOf(map.get("num"))));
                 getCell(row,cellNum++).setCellValue(String.valueOf(map.get("status")));

                 Order order = new Order(orderId);
                 order.setStatus("仓库打包");
                 orderService.save(order);
             }
            exportData(response,"订单 - 大仓库.xlsx",workbook);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 下载导入数据模板
     */
    @RequestMapping(value = "importTemplate")
    public void importTemplate(HttpServletResponse response) {
        importTemplate(response,"订单 - 大仓库.xlsx");
    }

    /*
     * 读取Excel到列表
     */
    private List<Order> readExcelToList(MultipartFile file){
        try {
            List<Order> orders = new ArrayList<>();
            Workbook workbook = getWorkbook(file);
            Sheet sheet = workbook.getSheetAt(0);
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (row == null  || row.getLastCellNum() < 9) {
                    continue;
                }
                String orderId = getCellValue(row,1);
                if(StringUtils.isBlank(orderId)){
                    continue;
                }
                Order order = new Order();
                order.setId(orderId);
                order.setStatus(getCellValue(row,6));
                order.setWaybillNo(getCellValue(row,8));
                order.setExpressCompany(getCellValue(row,7));
                order.setDeliveryDate(Date.valueOf(getCellValue(row,9)));
                orders.add(order);
            }
            return orders;
        } catch (Exception ex) {
            throw ex;
        }
    }

    /*
     * 读取Excel到列表
     */
    private String check(List<Order> orders){
        return "";
    }

    /**
     * 导入数据
     */
    @ResponseBody
    @PostMapping(value = "importData")
    public String importData(MultipartFile file) {
        try {
            List<Order> orders = readExcelToList(file);
            String msg = check(orders);
            if(StringUtils.isNotBlank(msg)){
                return renderResult(Global.FALSE, "导入出错:" + msg);
            }
            for (Order order : orders){
                orderService.save(order);
            }
            return renderResult(Global.TRUE,"导入成功");
        } catch (Exception ex) {
            return renderResult(Global.FALSE, "导入出错:" + ex.getMessage());
        }
    }

    /**
     * 查询列表
     */
    @RequestMapping(value = {"service", ""})
    public String service(Order order, Model model) {
        model.addAttribute("order", order);
        return "modules/storage/order/service/list";
    }

    /**
     * 查询列表数据
     */
    @RequestMapping(value = "serviceData")
    @ResponseBody
    public Page<Map> serviceData(Order order,HttpServletRequest request, HttpServletResponse response) {
        Page page = new Page<>(request, response);
        return orderService.getServiceListForManage(order.getServiceStatus(),page.getPageSize(),page.getPageNo());
    }

    /**
     * 系统审核【同意】
     * @param orderId 订单Id【订单】
     * @return 系统审核
     */
    @RequestMapping(value = "service/agree")
    @ResponseBody
    public String sysAgree(String orderId) {
        try{
            orderService.sysAudit(orderId,"同意",null);
            return renderResult(Global.TRUE, text("审批完成！"));
        }catch (Exception ex){
            return renderResult(Global.FALSE, text(ex.getMessage()));
        }
    }

    /**
     * 系统审核【拒绝】
     * @param orderId 订单Id【订单】
     * @param reason 原因
     * @return 系统审核
     */
    @RequestMapping(value = "service/reject")
    @ResponseBody
    public String sysReject(String orderId,String reason) {
        try{
            orderService.sysAudit(orderId,"拒绝",reason);
            return renderResult(Global.TRUE, text("审批完成！"));
        }catch (Exception ex){
            return renderResult(Global.FALSE, text(ex.getMessage()));
        }
    }

    /**
     * 收到退货
     * @param orderId 订单Id【订单】
     * @return 收到退货
     */
    @RequestMapping(value = "service/signed")
    @ResponseBody
    public String signed(String orderId) {
        try{
            orderService.signed(orderId);
            return renderResult(Global.TRUE, text("操作完成！"));
        }catch (Exception ex){
            return renderResult(Global.FALSE, text(ex.getMessage()));
        }
    }
}